#!/usr/bin/env node

const http = require('http'),
        log = console.log;

let items = [];

http.createServer((req, res) => {
    log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
    log(items);
    switch(req.method) {
        case 'GET':
          select(req,res);
          break
        case 'PUT':
          res.end('put')
          break;
        case 'POST':
          insert(req,res)
          break;
        case 'DELETE':
          res.end('delete');
          break;
        default:
          res.end('request method not support');
  }
}).listen(8080);

function select(req,res){
  //解决跨域问题 8080和3000
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.end(JSON.stringify(items));
}

function insert(req,res){
  let item = '';
  req.on('data',chunk=>item+=chunk);
  req.on('end',()=>{
    item = new URLSearchParams(item);
    item = item.get('item');
    if(item!==''||typeof item !== 'undefined'){
      items.push(item);
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.end('insert ok!');
    } else {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.end('items empty');
    }
  });
}

//02运行静态页面--http://192.168.142.166:3000/index.html
//index.html里面引入main.js--请求8080端口的数据内容
//12-rest-api监听8080端口，post上传数据curl -X POST -d "item=hello" http://localhost:8080/
//上传的数据在浏览器里显示
//点击提交按钮在浏览器显示输入框内容

